import 'package:flutter/material.dart';
import 'package:jm_flutter/jm_flutter.dart';

import 'my_pop_menu_item.dart';

typedef ContextMenuBuilder = List<MyPopMenuItem> Function(BuildContext context);

class MyPopMenu extends StatelessWidget {
  final tag = "MyPopMenu";

  /// The widget displayed inside the [MyPopMenu]
  final Widget child;

  final ContextMenuBuilder builder;

  //触发方式
  final bool isLongPress;
  final bool isRightClick;
  final bool isTap;

  const MyPopMenu({
    Key? key,
    required this.child,
    required this.builder,
    this.isLongPress = true,
    this.isRightClick = true,
    this.isTap = true,
  }) : super(key: key);

  void _showContextMenu(BuildContext context) {
    final size = context.findRenderObject()?.paintBounds.size;
    //获取位置
    var offset =
        context.findRenderObject()?.getTransformTo(null).getTranslation();
    //logd(tag, "_showContextMenu size: $size, offset: ${offset?.x},${offset?.y}");

    if (size == null || offset == null) {
      return;
    }

    openDialog(
      PopContextMenu(
        size: size,
        position: Offset(offset.x, offset.y),
        builder: builder,
        // verticalPadding: verticalPadding,
        // width: width,
      ),
      barrierColor: Colors.transparent,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onSecondaryTapDown: (details) {
        if (isRightClick) {
          _showContextMenu(context);
        }
      },
      onTap: () {
        if (isTap) {
          _showContextMenu(context);
        }
      },
      onLongPressStart: (details) {
        if (isLongPress) {
          _showContextMenu(context);
        }
      },
      child: Container(color: Colors.transparent, child: child),
    );
  }
}

class PopContextMenu extends StatefulWidget {
  final Size size;
  final Offset position;
  //final EdgeInsets? margin;

  final ContextMenuBuilder builder;

  const PopContextMenu({
    super.key,
    required this.position,
    required this.builder,
    required this.size,
  });

  @override
  State<PopContextMenu> createState() => _PopContextMenuState();
}

class _PopContextMenuState extends State<PopContextMenu> {
  final tag = "PopContextMenu";

  late List<MyPopMenuItem> children;

  double height = 0;

  double? top;
  double? left;
  double? right;
  double? bottom;

  double get width => MyPopMenuItem.menuItemWidth;

  Size get size => widget.size;
  Offset get position =>
      Offset(widget.position.dx, widget.position.dy - MyScreen.statusBarHeight);

  //double get dy => position.dy - MyScreen.statusBarHeight;

  double get bottomMax =>
      MyScreen.screenHeight -
      MyScreen.statusBarHeight -
      MyScreen.bottomBarHeight;

  @override
  void initState() {
    // TODO: implement initState
    //final children = widget.builder(context);

    //最后一个不显示分割线

    children =
        widget.builder(context).where((element) => element.visible).toList();
    children.last.isDivider = false;

    height = children.length * MyPopMenuItem.menuItemHeight;

    if (height >
        (MyScreen.screenHeight -
            MyScreen.statusBarHeight -
            MyScreen.bottomBarHeight -
            size.height -
            4)) {
      height = MyScreen.screenHeight -
          MyScreen.statusBarHeight -
          MyScreen.bottomBarHeight -
          size.height -
          4;
    }

    //logd(tag, "position: ${position.dx},${position.dy}, height: $height, bottomMax: $bottomMax");

    top = (position.dy) + size.height + 4;

    //logd(tag, "top: $top , top! + height: ${top! + height}");
    if ((top! + height) > bottomMax) {
      top = null;
      bottom = MyScreen.screenHeight -
          MyScreen.statusBarHeight -
          MyScreen.bottomBarHeight -
          position.dy +
          4;
    }

    left = position.dx;
    if (left! < 12) {
      left = 12;
    } else if (left! + width > MyScreen.screenWidth) {
      left = MyScreen.screenWidth - width - 12;
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          right: right,
          left: left,
          bottom: bottom,
          top: top,
          child: Container(
            decoration: const BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black26,
                  offset: Offset(0, 0),
                  blurRadius: 48.0,
                  spreadRadius: 0.0,
                ),
              ],
            ),
            child: SizedBox(
              width: width,
              height: height,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12.0),
                child: Material(
                  color: const Color(0xFFF6F6F6),
                  child: ListView(
                    primary: false,
                    shrinkWrap: true,
                    children: children,
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
